import React, { useEffect, useState } from 'react'
import systemStore,{SystemStore} from '../../store/SystemStore'
import config from './../../../package.json'
type ManualUpdateProps = {}
import './ManualUpdate.less'
import axios from 'axios'
import utils from '../../utils/utils'
import ipcRender from '../../ipcRender'
const ManualUpdate = function(props:ManualUpdateProps){
  /**
   * 新版本地址
   */
  const [newVersion, setNewVersion] = useState('')
  const [versionUrl, setVersionUrl] = useState('')
  const checkUpdate = async ()=>{
    const updateRoot = SystemStore.apiUrl.replace(/\:\d+.*/ig,'')
    const downloadRoot = `http://47.97.61.50:9000/`;
    let feedUrl = updateRoot + '/latest.yml?rnd='+Math.random()
    const xml = await axios.get(feedUrl);
    const xmlstr = xml.data+''
    const versionRegex = /version:\s*([\d.]+)/;
    const match = xmlstr.match(versionRegex);
    
    const currentVersion:string = await new Promise((resolve)=>{
      ipcRender.getAppRevision().then((rev)=>{
        const version = rev?rev:config.version;
        resolve(version);
      }).catch(error=>{
        resolve('')
      })
    })
    
    const version = match ? match[1] : null;
    console.log('当前版本',currentVersion,version,utils.compareVersions(currentVersion,version ))
    if( version && utils.compareVersions(version, currentVersion)> 0){
      // 有新版本
      const url = downloadRoot +`im-server/AppRelease/LightChat-Setup-${version}.exe`
      setVersionUrl(url);
      setNewVersion(version)
    }
  }
  useEffect(()=>{
    checkUpdate()
  },[])
  return <>
    { newVersion? <div className="manual-update">发现新版本：{newVersion} <a onClick={e=>{
      const url = versionUrl
      const name = url.substring(url.lastIndexOf('/')+1)
      ipcRender.downloadFile( url, name )
    }}>手动下载</a></div> :null}
  </>
}

export default ManualUpdate
